package com.lxy.equipment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxy.common.domain.common.R;
import com.lxy.equipment.domain.po.Equipment;
import com.lxy.equipment.domain.vo.EquipmentVO;
import com.lxy.equipment.mapper.EquipmentMapper;
import com.lxy.equipment.properties.IoTDBProperties;
import com.lxy.equipment.service.EquipmentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.iotdb.isession.SessionDataSet;
import org.apache.iotdb.session.Session;
import org.apache.tsfile.read.common.RowRecord;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment> implements EquipmentService {

    private final IoTDBProperties ioTDBProperties;


    @Override
    public R<List<EquipmentVO>> getAllEquipment() {
        //在Mysql数据库中查找数据,筛选运行正常的设备
        LambdaQueryWrapper<Equipment> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Equipment::getStatus,1);
        List<Equipment> list = list(lambdaQueryWrapper);
        List<EquipmentVO> equipmentVOS=new ArrayList<>();
        for (Equipment equipment : list) {
            EquipmentVO equipmentVO=new EquipmentVO();
            BeanUtils.copyProperties(equipment,equipmentVO);
            equipmentVOS.add(equipmentVO);
        }
        return R.ok(equipmentVOS);
    }


    //TODO IOTDB与Mysql同步数据，使用SpringTask实现
    public void temp(){
        //IoTDB数据库建立连接
        Session session=new Session.Builder()
                .host(ioTDBProperties.getHost())
                .port(ioTDBProperties.getPort())
                .username(ioTDBProperties.getUserName())
                .password(ioTDBProperties.getPassWord())
                .build();
        try{
            session.open(false);
            session.setFetchSize(10000);
            //查找数据
            String sql = "SHOW DEVICES root.transformerSubstation.*";
            SessionDataSet dataSet = session.executeQueryStatement(sql);
            //封装数据
            List<EquipmentVO> equipmentVOS=new ArrayList<>();
            while(dataSet.hasNext()){
                EquipmentVO equipmentVO=new EquipmentVO();

                RowRecord record = dataSet.next();
                String device = record.getFields().get(0).getStringValue();
                equipmentVO.setEquipmentName(device);
            }
            session.close();

        }catch (Exception e){


        }


    }

}
